<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * Controlador para gerir a autenticação
 */
class Auth extends CI_Controller {
	
	/**
         * Controlador de login
         */
	public function login(){
			$this->load->model("auth_model");
			
			
                        if ($this->input->post("login_form")){
                            $username = $this->input->post("username");
                            $password = $this->input->post("password");
                            if ($this->authenticate($username, $password)){
                                    $this->redirect_to_home();
                            }else{
                                    echo "Wrong Login";
                                    $this->load->view('auth/login');
                            }
                        }
                        $this->redirect_to_home();
	}

        
        /*
         * Redirecciona o utilizador para a devida pagina
         */
        private function redirect_to_home(){
            if (is_logged_in()){
                $username = $this->session->userdata("username");
                $type=substr($username, 0, 1);
                switch ($type) {
                    case "m":
                        redirect("medico/home");
                        break;
                }
            }else{
                
                $content = $this->load->view("auth/login",'',true);
                $this->load->view('common/header');
                $this->load->view('common/sidebar');
                $this->load->view('common/content', array("html"=>$content));
                $this->load->view('common/footer');
            }
        }

	
	/**
	 * 
	 * Autentica o utilizador no sistema
	 * @param unknown_type $username
	 * @param unknown_type $password
	 */
	private function authenticate($username, $password){
		$result = $this->auth_model->validate_login(
			$username,
			$password
		);
		if ($result==true){
                    $this->session->set_userdata("username",$username);
			$this->session->set_userdata("logged_in",1);
		}
		return $result;
	}
	
        
        /**
         * Faz logout do utilizador e redirecciona para a raiz do site
         */
	public function logout(){
		$this->session->unset_userdata("logged_in");
		redirect("/");
	}
        
        public function forbidden(){
            $content = $this->load->view("auth/forbidden",'',true);
            $this->load->view('common/header');
            $this->load->view('common/sidebar');
            $this->load->view('common/content', array("html"=>$content));
            $this->load->view('common/footer');
        }
}